package pers.qianyu.month_202101.date_20210113;

import org.junit.*;

/**
 * 394. 字符串解码
 * https://leetcode-cn.com/problems/decode-string/
 *
 * @author mizzle rain
 * @date 2021-01-13 18:42
 */
public class DecodeString {
    public String decodeString(String s) {
        int len = s.length();
        if (len == 0) return "";
        String res = "";
        for (int i = 0; i < s.length(); ) {
            char ch = s.charAt(i);
            if (!Character.isDigit(ch)) {
                res += ch;
                i++;
            } else {
                int k = 0;
                while (Character.isDigit(s.charAt(i))) k = k * 10 + (s.charAt(i++) - '0');
                int j = i + 1, count = 1;
                while (count > 0) {
                    if (s.charAt(j) == '[') count++;
                    if (s.charAt(j++) == ']') count--;
                }
                String s1 = decodeString(s.substring(i + 1, j - 1));
                while (k-- > 0) res += s1;
                i = j;
            }
        }
        return res;
    }

    @Test
    public void test1() {
        String result = new DecodeString().decodeString("3[a]2[bc]");
        System.out.println("result = " + result);
        Assert.assertEquals(result, "aaabcbc");
    }

    @Test
    public void test2() {
        int k = 3;
        while (k-- > 0) System.out.println(1);
    }
}
